//app.js
import URL from './baseurl'
import pub from './pub.js'
import axios from 'axios'

var config = {
  onLaunch: function () {
    let self = this;
    // 利用是否缓存sessionId 判断是否登录
    if (!uni.getStorageSync('sessionId')) { // 缓存sessionId为空
      uni.navigateTo({
        url: '/pages/main/login/login',
      })
    } else { // 缓存sessionId存在
	  self.header['wxa-sessionid'] = uni.getStorageSync('sessionId');
      uni.request({
        url: URL + '/app/base/getLoginInfo',
        header: self.header,
        success(res) {
          if(res.data.code==='0'){
			  self.globalData.userInfo = res.data.wxUser;
			  if(res.data.user){
			  	  self.globalData.userInfo.mobile = res.data.user.mobile;
				  self.globalData.user = res.data.user;
			  }else{
				  self.goLogin()
			  }
			  uni.$emit('userInfo', 'ok')
		  }else if(res.data.code==='-2001'){
			  self.goLogin()
		  }else{
			  uni.showToast({
			  	title: res.data.message,
				icon: 'none'
			  })
		  }
          // console.log(self.globalData.userInfo, '用户信息')
        }
      })
    }
    // 展示本地存储能力
    var logs = uni.getStorageSync('logs') || []
    logs.unshift(Date.now())
    uni.setStorageSync('logs', logs)

    // 登录
    // wx.login({
    //   success: res => {
    //     // 发送 res.code 到后台换取 openId, sessionKey, unionId
    //   }
    // })
    // 获取用户信息
    // wx.getSetting({
    //   success: res => {
    //     if (res.authSetting['scope.userInfo']) {
    //       // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
    //       wx.getUserInfo({
    //         success: res => {
    //           // 可以将 res 发送给后台解码出 unionId
    //           this.globalData.userInfo = res.userInfo

    //           // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
    //           // 所以此处加入 callback 以防止这种情况
    //           if (this.userInfoReadyCallback) {
    //             this.userInfoReadyCallback(res)
    //           }
    //         }
    //       })
    //     }
    //   }
    // })
  },
  goLogin(){
	  uni.navigateTo({
		  url: '/pages/main/login/login',
	  })
  },
  getLoginInfo(){
	let self = config;
	uni.request({
	  url: URL + '/api/base/getLoginInfo',
	  header: self.header,
	  success(res) {
		if(res.data.code==='0'){
		  self.globalData.userInfo = res.data.wxUser;
		  if(res.data.user){
			  // self.globalData.userInfo.mobile = res.data.user.mobile;
			  self.globalData.user = res.data.user;
		  }else{
			  self.goLogin()
		  }
		  uni.$emit('userInfo', 'ok')
		}else if(res.data.code==='-2001'){
		  self.goLogin()
		}else{
		  uni.showToast({
			title: res.data.message,
			icon: 'none'
		  })
		}
	    // console.log(self.globalData.userInfo, '用户信息')
	  }
	})
  },
  // 判断是否为警员
  jugeIsPolice(){
  	let self = this;
  	uni.showLoading({title: '加载中',mask: true});
  	config.post('/app/base/getIsPolice', {}).then(res=>{
  		uni.hideLoading();
  		if(res.data.code==='0'){
  			// 如果是警员
  			if(res.data.isPolice){
				config.globalData.isPolice = true;
  			}
  		}else{
  			uni.showToast({title: self.config.handleError(res.data),icon: 'none'});
  		}
  	})
  },
  globalData: {
    userInfo: {},
	user: {},
    location: {},
    address: [],
	isPolice: false
  },
  header: {
    // 'content-Type': 'application/json',
    'content-type': 'application/x-www-form-urlencoded',
    'token': uni.getStorageSync('token')||''
  },
  URL: URL,
  pub: pub,
  // 以下为异步请求相关
  toUrl: (obj) => {
    let str = '';
    for (let i in obj) {
      str += '&' + i + '=' + obj[i] || '';
    }
    str = str.substr(1);
    return str;
  },
  get: (url, obj) => {
    // return axios.get(URL + url + '?' + config.toUrl(obj));
  	// #ifdef MP-WEIXIN
  		// console.log('5+App平台');
  		return new Promise((resolve, reject)=>{
  			uni.request({
  				url: URL + url,
  				method: 'GET',
				header: config.header,
  				data: config.toUrl(obj),
  				success: (res) => {resolve(res);},
  				fail: (err) => {reject(err)},
  				complete: () => {}
  			});
  		})
  	// #endif
  	// #ifdef H5
  		// console.log('H5平台');
  		return axios({
  			url:URL+url,
  			method: 'GET',
  			// data: Qs.stringify(obj),
  			data: config.toUrl(obj),
  			withCredentials: true,
  			xhrFields: {withCredentials: true},
  			headers: {
  				'Content-Type': 'application/x-www-form-urlencoded',
  			},
  		});
  	// #endif
  },
  post: (url, obj) => {
    // return axios.post(URL + url + '?' + config.toUrl(obj));
  	// #ifdef MP-WEIXIN
  		// console.log('5+App平台');
  		return new Promise((resolve, reject)=>{
  			uni.request({
  				url: URL+url,
  				method: 'POST',
				header: config.header,
  				data: obj,
  				success: (res) => {resolve(res);},
  				fail: (err) => {reject(err)},
  				complete: () => {}
  			});
  		})
  	// #endif
  	
  	// #ifdef H5
  	return axios({
  		url:URL+url,
  		method: 'POST',
  		// data: Qs.stringify(obj),
  		data: config.toUrl(obj),
  		// headers:{
  		//     'Content-Type':'application/json;charse=UTF-8'
  		// },
  		withCredentials: true,
  		xhrFields: {withCredentials: true},
  		headers: {
  			'Content-Type': 'application/x-www-form-urlencoded',
  		},
  	});
  	// #endif
  },
  // 处理错误信息
  handleError: (data) => {
    if (data.code === "-1001") {
      return data.message;
    } else if (data.code === "-2001") {
        uni.navigateTo({
        	url: '/pages/main/login/login'
        })
  		return data.message;
        // 利用缓存重新登录
        // this.storageLogin();
    } else {
      return data.message || '异常';
    }
  },
  // 文件上传-阿里云OSS方法
  upload(fileUrl, callback, progress){
  	config.post('/common/upload/getUploadPolicyAndSign', {}).then(resu=>{
  		let info = resu.data;
		let suffix = fileUrl.substr(fileUrl.indexOf(".")); // 获取文件后缀名
  		let imgName = info.dir + (new Date().getTime()) + suffix;
  		let uploadTask = uni.uploadFile({
  			url: info.host,
  			filePath: fileUrl,
  			name: 'file',
  			formData: {
  				'key': imgName, // 文件名
  				'policy': info.policy,
  				'OSSAccessKeyId': info.accessid,
  				'signature': info.signature,
  				'success_action_status': '200',
  			},
  			success: (res, op) => {
  				let newFileUrl = info.host+'/'+imgName;  // 最终文件路径
  				if(callback) callback(newFileUrl);
  			},
  			fail: (err) => {
  				console.log(err)
  				err.wxaddinfo = info.host;
  			},
  			complete: (complete) => {
  				console.log(complete)
  			}
  		})
		// uploadTask.onProgressUpdate(res=>{
		// 	// console.log("上传进度" + res.progress);
		// 	if(progress) {progress(res.progress)}
		// })
  	})
  },
  // websocket连接
  wsConnect(){
	  uni.connectSocket({
	    url: 'wss://chang2.xiao2yun.com/ws'+'?is_operator=0&mobile='+config.globalData.userInfo.mobile,
	    // url: 'ws://192.168.0.110:10001'+'?is_operator=0&mobile='+config.globalData.userInfo.mobile,
	  });
	  
	  uni.onSocketOpen(function () {
		  console.log('WebSocket 已连接！');
		  uni.$emit('wsOpen', 'ok')
	  });
	  
	  uni.onSocketClose(function (res) {
	    console.log('WebSocket 已关闭！');
		uni.$emit('wsOpen', 'no')
	  });
  },
  
  //验证是否实名认证
  isRealPerson(callback, fail){
  	config.get('/app/base/getIsAuthentication', {}).then(res=>{
		console.log(res.data)
		if(res.data.code==0){
			callback(res.data.isAuthentication)
		}else{
			fail()
		}
	})
  }
}

export default config;